import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/entity/article_entity.dart';
import 'package:flutter_wanandroid/entity/banner_entity.dart';
import 'package:flutter_wanandroid/entity/common_entity.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/login_page.dart';
import 'package:flutter_wanandroid/res/colors.dart';
import 'package:flutter_wanandroid/utils/y_toast.dart';
import 'package:fluttertoast/fluttertoast.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  EasyRefreshController? _easyRefreshController;

  SwiperController? _swiperController;

  int _page = 0;
  bool hasMore = true;
  String? bannerUrl;
  String? articleUrl;

  List<BannerDataBean>? bannerDatas = [];
  List<DatasBean>? articleDatas = [];

  @override
  void initState() {
    super.initState();

    _easyRefreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);
    _swiperController = SwiperController();
    bannerUrl = Api.BASE_URL + Api.BANNER;
    articleUrl = "${Api.BASE_URL}${Api.ARTICLE_LIST}$_page/json";
    // getHttp();
    getHttpUtil();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // body: Text("http"),
      body: EasyRefresh.builder(
        controller: _easyRefreshController,
        header: const PhoenixHeader(
          skyColor: YColors.colorPrimary,
          position: IndicatorPosition.locator,
          safeArea: false,
        ),
        footer: const PhoenixFooter(
          skyColor: YColors.colorPrimary,
          position: IndicatorPosition.locator,
        ),
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 1), () {
            if (!mounted) {
              return;
            }
            setState(() {
              _page = 0;
            });
            // getHttp();
            getHttpUtil();
            _easyRefreshController?.finishRefresh();
            _easyRefreshController?.resetFooter();
          });
        },
        onLoad: () async {
          Future.delayed(const Duration(seconds: 1), () {
            if (!mounted) {
              return;
            }
            setState(() {
              _page++;
            });
            getMoreData();
            _easyRefreshController?.finishLoad(
                hasMore ? IndicatorResult.success : IndicatorResult.noMore);
          });
        },
        childBuilder: (context, physics) {
          return CustomScrollView(
            physics: physics,
            slivers: [
              SliverAppBar(
                backgroundColor: Theme.of(context).primaryColor,
                expandedHeight: MediaQuery.of(context).size.width / 1.8 * 0.8 +
                    20, // +20 是上下的padding值

                pinned: false,

                flexibleSpace: FlexibleSpaceBar(
                  background: getBanner(),
                ),
              ),
              const HeaderLocator.sliver(),
              SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  return getRow(index, articleDatas!.length);
                }, childCount: articleDatas!.length),
              ),
              const FooterLocator.sliver(),
            ],
          );
        },
      ),
    );
  }

  Widget? getRow(int i, int length) {
    if (length == 0) {
      return null;
    }
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
        child: ListTile(
          leading: IconButton(
            icon: articleDatas != null && (articleDatas![i].collect ?? true)
                ? Icon(Icons.favorite, color: Theme.of(context).primaryColor)
                : Icon(Icons.favorite_border),
            tooltip: "收藏",
            onPressed: () {
              print("点击收藏按钮");
              Fluttertoast.showToast(
                msg: "点击收藏按钮",
              );
              if (articleDatas![i].collect == true) {
                cancelCollect(articleDatas![i].id);
              } else {
                addCollect(articleDatas![i].id);
              }
            },
          ),
          title: Text(
            articleDatas![i].title ?? "",
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          subtitle: Padding(
            padding: EdgeInsets.only(top: 10),
            child: Row(
              children: [
                Container(
                  constraints: const BoxConstraints(maxWidth: 150),
                  padding: const EdgeInsets.symmetric(horizontal: 6),
                  decoration: BoxDecoration(
                    border: Border.all(
                        color: Theme.of(context).primaryColor, width: 1),
                    borderRadius: BorderRadius.circular(20), //圆角度
                  ),
                  child: Text(
                    articleDatas![i].superChapterName!,
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  child: Text(
                    articleDatas![i].author!,
                  ),
                )
              ],
            ),
          ),
          trailing: const Icon(Icons.chevron_right),
        ),
      ),
      onTap: () {
        print("点击进入到下一页");
        Fluttertoast.showToast(
            msg: "点击进入到下一页",
            toastLength: Toast.LENGTH_SHORT,
            textColor: Colors.white,
            backgroundColor: Theme.of(context).primaryColor);
      },
    );
  }

  Widget getBanner() {
    return Container(
      width: MediaQuery.of(context).size.width,

      //1.8是banner宽高比，0.8是viewportFraction的值
      height: MediaQuery.of(context).size.width / 1.8 * 0.8,
      padding: EdgeInsets.only(top: 10, bottom: 10),
      child: Swiper(
        itemCount: bannerDatas!.length,

        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0),
                image: DecorationImage(
                  image: NetworkImage(bannerDatas![index].imagePath!),
                  fit: BoxFit.fill,
                )),
          );
        },
        loop: false,

        autoplay: false,
        autoplayDelay: 3000,
        //触发时是否停止播放
        autoplayDisableOnInteraction: true,
        duration: 600,
        //默认分页按钮
        controller: _swiperController!,
        //默认指示器
        pagination: SwiperPagination(
          // SwiperPagination.fraction 数字1/5，默认点
          builder: DotSwiperPaginationBuilder(size: 6, activeSize: 9),
        ),

        //视图宽度，即显示的item的宽度屏占比
        viewportFraction: 0.8,
        //两侧item的缩放比
        scale: 0.9,

        onTap: (int index) {
          //点击事件，返回下标
          print("index-----" + index.toString());
        },
      ),
    );
  }

  void getHttp() async {
    getHttpBanner();
    getHttpArticle();
  }

  void getHttpBanner() async {
    final dio = Dio();
    Response bannerRes = await dio.get(bannerUrl!);
    Map<String, dynamic> bannerMap = json.decode(bannerRes.toString());
    BannerEntity? entity = BannerEntity.fromMap(bannerMap);
    print(entity);
    setState(() {
      if (entity != null) {
        bannerDatas = entity.data;
      }
    });
  }

  void getHttpArticle() async {
    final dio = Dio();
    Response articleRes = await dio.get(articleUrl!);
    Map<String, dynamic> articleMap = json.decode(articleRes.toString());
    ArticleEntity? articleEntity = ArticleEntity.fromMap(articleMap);
    setState(() {
      if (articleEntity != null && articleEntity.data != null) {
        articleDatas = articleEntity.data!.datas;
      }
    });
    print(articleEntity);
  }

  Future getMoreData() async {
    articleUrl = "${Api.BASE_URL}${Api.ARTICLE_LIST}$_page/json";
    final dio = Dio();
    Response articleRes = await dio.get(articleUrl!);
    Map<String, dynamic> articleMap = json.decode(articleRes.toString());
    ArticleEntity? articleEntity = ArticleEntity.fromMap(articleMap);
    setState(() {
      if (articleEntity != null && articleEntity.data != null) {
        articleDatas?.addAll(articleEntity.data!.datas!);
        if (articleEntity.data!.datas!.isEmpty ||
            articleEntity.data!.datas!.length < 10) {
          hasMore = false;
        }
      }
    });
  }

  void getHttpUtil() async {
    Response bannerRes = await HttpUtil().get(Api.BANNER);
    Map<String, dynamic> bannerMap = json.decode(bannerRes.toString());
    BannerEntity? entity = BannerEntity.fromMap(bannerMap);

    Response articleRes = await HttpUtil().get(articleUrl!);
    Map<String, dynamic> articleMap = json.decode(articleRes.toString());
    ArticleEntity? articleEntity = ArticleEntity.fromMap(articleMap);

    print(entity);
    if (mounted) {
      setState(() {
        if (entity != null) {
          bannerDatas = entity.data;
        }
        if (articleEntity != null && articleEntity.data != null) {
          articleDatas = articleEntity.data!.datas;
        }
      });
    }
  }



  void cancelCollect(int? id) async {
    if (null == int) {
      return;
    }
    var collectResponse =
        await HttpUtil().post("${Api.UN_COLLECT_ORIGIN_ID}$id/json");
    Map<String, dynamic> map = json.decode(collectResponse.toString());
    var commonEntity = CommonEntity.fromMap(map);
    if (commonEntity.errorCode == -1001) {
      YToast.showBottom(commonEntity.errorMsg ?? "", context);
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => LoginPage()));
    } else {
      YToast.showBottom("取消成功", context);
      getHttpUtil();
    }
  }

  void addCollect(int? id) async {
    if (null == int) {
      return;
    }
    var collectResponse = await HttpUtil().post(Api.COLLECT + "$id/json");
    Map<String, dynamic> map = json.decode(collectResponse.toString());
    var commonEntity = CommonEntity.fromMap(map);
    if (commonEntity.errorCode == -1001) {
      YToast.showBottom(commonEntity.errorMsg ?? "", context);

      Navigator.push(
          context, MaterialPageRoute(builder: (context) => LoginPage()));
    } else {
      YToast.showBottom("收藏成功", context);
      getHttpUtil();
    }
  }

  @override
  void dispose() {
    _easyRefreshController?.dispose();
    _swiperController?.stopAutoplay();
    _swiperController?.dispose();
    super.dispose();
  }
}
